﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Linq;

namespace Lincolnwood.Foundation.Common.Data.NHibernate
{
    public abstract class NHibernateRepositoryBase<TAggregateRoot, TKey> : NHibernateReferenceDataRepositoryBase<TAggregateRoot, TKey>, IReadWriteRepository<TAggregateRoot, TKey> 
        where TAggregateRoot : EntityBase<TKey> 
        where TKey : struct
    {

        protected NHibernateRepositoryBase(NHibernateUnitOfWork unitOfWork): base(unitOfWork)
        {
        }

       
        public TAggregateRoot Add(TAggregateRoot aggregate)
        {
            UnitOfWork.Session.SaveOrUpdate(aggregate);
            return aggregate;
        }

        public void RemoveById(TKey id)
        {
            UnitOfWork.Session.Delete(UnitOfWork.Session.Load<TAggregateRoot>(id));
        }

        public TAggregateRoot FindById(TKey id)
        {
            return UnitOfWork.Session.Get<TAggregateRoot>(id);
        }

        public int GetCount()
        {
            int count = UnitOfWork.Session.Query<TAggregateRoot>().Count();
            return count;
        }

        public IEnumerable<TAggregateRoot> All()
        {
            var query = UnitOfWork.Session.Query<TAggregateRoot>();
            return query.ToList<TAggregateRoot>();
        }

        public abstract void Merge(TAggregateRoot entity);
    }
}
